var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var page = 1;
var loadingMore = false;
var hasMore = true;
var screen_w = 320;
var tc=0;
Page({

   data: {
     util:util,
     uid:0,
     token: '',
     waithao: 0,
     content_item_w: 100,
     goodTypeView_w: 100,
     colorSet: '',
     myhao:'',
     postuid:'',
     numberV:'',

     bottom_nav_data: [],
     isIphone_x: false,
     nav_bgColor: '#ffffff',

     verified:false, //是否已通过咨客


     ghsList: [],//picker中range属性值
     ghsIndex: 0,//picker中value属性值
     btimeold: ["請選擇時間", "上午09-10點", "上午10-11點", "下午14-15點", "下午15-16點", "下午16-17點", "晚上18-19點", "晚上19-20點", "晚上20-21點",],
    btime: [
    { value: "上午09-10點", number: 0 ,counts:0},
    { value: "上午10-11點", number: 0, counts: 0},
    { value: "下午14-15點", number: 0, counts: 0},
    { value: "下午15-16點", number: 0, counts: 0}, 
    { value: "下午16-17點", number: 0, counts: 0}, 
    { value: "晚上18-19點", number: 0, counts: 0}, 
    { value: "晚上19-20點", number: 0, counts: 0}, 
    { value: "晚上20-21點", number: 0, counts: 0}],
    btimeIndex: 0, 
    project: ["請選擇項目", "到店購買"],
    //  中國服務預約  香港維修服務預約  香港裝修面談會議預約  澳門維修服務預約  澳門裝修面談會議預約 
    projectIndex: 0, 
    username:'',
    address:'',
    
    contact_phone: '',

    currentDateStr: "",
    dayList: '',
    currentDayList: '',
    currentObj: '',
    currentDay: '',
    today:'',
    navFromDetail:false  

   },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var that = this;
    hasMore = true;
    page = 1;


    // that.setData({
    //   postuid: util.orgid
    // });
    that.getLoginUserInfo('');
    console.log('options', options);
    if (options.project) {
      this.setData({
        project: options.project,
        postuid: options.ghsid,
        ghsname: options.ghsname,
        navFromDetail: true

      })
    } else {
      if (options.isAdmin==1){
        this.setData({
          isAdmin: true
        })
      }
      that.getGhs(1);
    }
    that.getverified();

    var tc = app.get_tc();
    tc=tc;
    that.setData({
      tc: tc,
    })
    var titlename = tc == 1 ? '預約' : '预约';
    if (util.orgid == 20510) {
      titlename = tc == 1 ? '預約' : 'Reservation';
    }
    wx.setNavigationBarTitle({
      title: titlename,
    });
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('booktime/booktime', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });

    wx.getSystemInfo({
      success: function (res) {
    
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_w : res.windowWidth,
          screen_h : res.windowHeight,
          content_h: res.windowHeight - (isIphone_x?70:50)-123,
          content_w: res.windowWidth - 78,
          goodTypeView_w: (res.windowWidth - 78) / 3
        });
        
      }
    });

    //获取颜色配置
    app.getColorSetData(function (color) {
      var col = color.goods_col ? parseInt(color.goods_col) : 3;
      col = col > 0 ? col : 3;
      that.setData({
        colorSet: color,
        content_item_w: (screen_w - (col + 1) * 5) / col,
        goodTypeView_w: screen_w / 3
      })
    });
    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    })  

    var currentObj = this.getCurrentDayString()
    this.setData({
      currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
      currentDay: currentObj.getDate(),
      currentObj: currentObj,
      today: currentObj,
      date: (currentObj.getMonth() + 1) + '/' + util.formatNumber(currentObj.getDate()) + '/' + currentObj.getFullYear(),
      time: util.formatNumber(new Date().getHours()) + ':' + util.formatNumber(new Date().getMinutes()),      
    })

    this.setSchedule(currentObj);
    that.getWaithao();

    if(util.orgid==20510){
      that.setData({
        project: [tc == 1 ? "其他地區服務預約(網上會議)" : "Service Reservation for other regions via webmeeting",
          tc == 1 ? "香港維修服務預約":"Residential Repair Service Reservation(Hong Kong)",
          tc == 1 ? " 香港裝修面談會議預約" :"Face to face renovation Service Reservation(Hong Kong)",
          tc == 1 ? "澳門維修服務預約" :"Residential Repair Service Reservation(MACAU)",
          tc == 1 ? "澳門裝修面談會議預約" :"Face to face renovation Service Reservation(MACAU)"]
      })
    }
    

  },
  onShow: function () {
    this.getMyhao();
    
  },

  //判断用户是否是该门店咨客
  getverified:function(){
    var that = this;
     util.api({
      method: "get",
      data: {
        ac: "getverified",
        uid: that.data.uid,
        mendianId: that.data.postuid,
      },
      
      success: function (responseData) {
        console.log("getverified:", responseData.data);
        if(responseData.data.res == true){
          that.setData({
            verified:true
          })
        }else{
          that.setData({
            verified:false
          })
        }
        
      }
    });
  },

  getLoginUserInfo: function(inviteuid){
    var that = this;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token
        })

        util.api({
          data: {
            "uid": res.uid,
            "publickey": util.publiccode,
            "ac": "userinfo"
          },
          success: function (responseData) {
            console.log(responseData.data);
            that.setData({
              userinfo: responseData.data
            });
          }
        });
        if(util.orgid==20510){
          that.getMyhao();
          that.getAuth(res.uid, res.token);
        }
      } else {
        app.reAuthorize(reGetUserInfo);
      }
    }, inviteuid);

    //获取关于等信息
    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });
  },

  getGhs: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        // var ghsList = ["請選擇門店"],
        // var ghsList = [];
        var  ghsIdList = [];
        for (var i = 0; i < result.length; i++) {
          if (result[i].gcataid == '371'||1) {
            var uid = result[i].uid;
            var title = result[i].username;


            // ghsList.push(title);
            ghsIdList.push(uid);
          }
        }
        that.setData({
          ghsList: result,
          ghsIdList: ghsIdList,
          postuid: ghsIdList[0],
          ghsIndex: 0,
          project:result[0].project_list
        });

        that.getWaithao();

        // that.getMyhao();

      }
    });
  },
  
  //查询领号等待信息
  getWaithao:function(){
    var that = this;
    //查询领号等待数
    var privatekey = utilMd5.hexMD5(that.data.uid + 'waithao' + that.data.token);
    console.log("that.data.uid:"+that.data.uid+"that.data.token:"+that.data.token+"util.orgid:"+util.orgid);
     util.api({
      method: "post",
      data: {
        ac: "waithao",
        uid: that.data.uid,
        orgid: that.data.postuid, 
        privatekey: privatekey
      },
      
      success: function (responseData) {
        console.log("调试--查询领号等待信息接口:", responseData.data);
        that.setData({
          waithao: responseData.data,
        });
        that.getWaithaoConfig();
        
      }
    });
  },

  getWaithaoConfig:function(){
    var that = this;
    //查询领号等待数
    var privatekey = utilMd5.hexMD5(that.data.uid + 'getwaithaoConfig' + that.data.token);
    
     util.api({
      method: "post",
      data: {
        ac: "getwaithaoConfig",
        uid: that.data.uid,
        orgid: that.data.postuid, 
        privatekey: privatekey
      },
      
      success: function (responseData) {
        console.log("调试--getwaithaoConfig等待信息接口:", responseData.data);
        that.setData({
          waithaoConfig: responseData.data,
        });
        that.loadConfigToList();
        
      }
    });
  },
  
  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  //我的排号信息
  getMyhao:function(){
    
    var that = this;
    util.api({
      method: "get",
      data: {
        ac: "getmyhao",
        uid: that.data.uid,
        orgid: that.data.postuid,
        type:1
      },
      
      success: function (responseData) {
        console.log("调试--我的排号信息接口:", responseData.data);
        console.log("调试--我的排号号码:", responseData.data.number);
        var resultData = responseData.data;
        that.setData({
          myhao:resultData
        })
      }
    });
  },
   //领号接口
  formSubmit: function (e){

    var that = this;
    var tc = this.data.tc;
    // if (that.data.authData.verified != '1') {
    //   wx.showModal({
    //     title: tc == -1 ? 'You are not a member. Please register.' : tc == 1 ? '你不是會員，請註冊' : '你不是会员，请注册',
    //   })
    //   return
    // }
    console.log(e);
    
    if (e.detail.value.phone == '') {
      wx.showToast({
        title: util.orgid == 20510 ? (tc == 1 ? '請輸入手機號' : 'Telephone is required'):tc == 1 ? '請輸入手機號' :'请输入手机号',
      })
    } else if (e.detail.value.username == '') {
      wx.showToast({
        title: util.orgid == 20510 ? (tc == 1 ? '請輸入姓名' : 'Name is required') :tc == 1 ? '請輸入姓名' :'请输入姓名',
      })
    } else if (e.detail.value.project == 0 && !that.data.navFromDetail&&util.orgid!=20510) {
      wx.showToast({
        title: tc == -1 ? 'Project is required':tc == 1 ? '請選擇預約項目' :'请选择预约项目',
      })
    } else if (e.detail.value.btime == 0) {
      wx.showToast({
        title: tc == -1 ? 'Time is required':tc == 1 ? '請選擇預約時間' :'请选择预约时间',
      })
    } else if (e.detail.value.email == 0) {
      wx.showToast({
        title: tc == -1 ? 'Email required' : tc == 1 ? '郵箱不能為空' : '邮箱不能为空',
      })
    } else {
      that.checkCounts(function(result){
        if (result==true) {
          that.checkMyhao(function (result){
            if(result==true){
              console.log("checkMyhao---->result==true");              
              var privatekey = utilMd5.hexMD5(that.data.uid + 'yuyue' + that.data.token);
              console.log('that.data.date + that.data.time', that.data.date + '|' + that.data.time);
              var project = that.data.project;
              var projectIndex = that.data.projectIndex;
              var tc = that.data.tc;
              var project=tc == -1 ? project[projectIndex].project_eng : tc == 1 ? project[projectIndex].project_tc : project[projectIndex].project;
              util.api({
                method: "post",
                data: {
                  ac: "yuyue",
                  uid: that.data.uid,
                  orgid: that.data.postuid,
                  privatekey: privatekey,
                  userNum: "",
                  // btime: that.data.btimeold[e.detail.value.btime],
                  btime: that.data.date + '|' + that.data.time,
                  username: e.detail.value.username,
                  // project: that.data.navFromDetail ? that.data.project : that.data.project[e.detail.value.project],
                  project: that.data.navFromDetail ? that.data.project : project,
                  phone: e.detail.value.phone,
                  email: e.detail.value.email,
                  catatype: 20,
                  address: e.detail.value.address,
                  type: 1
                },

                success: function (responseData) {
                  console.log("调试--预约接口接口:", responseData.data);
                  // http://admin.jawanology.com/api/gzhtuisong.php?ac=tuisong&appid=wx7053b9e0fc259526&secret=eb5c1e2380c1bc10b26d578211649552&binduid=15938&project=到店購買&name=zum&phone=13999999999&ghsname=水達人XX店&btime=8/30/2018|09:00
                  if (responseData.data.res == true) {
                    var contentname = util.orgid == 20510 ? (tc == 1 ? '已成功預約' : '已成功預約') :tc == 1 ? '已成功預約' : '已成功预约';
                    // wx.showToast({
                    //   title: contentname,
                    // })
                    app.dialogToast(contentname, "success", function () {
                      // wx.reLaunch({
                      //   url: '/pages/booktime/booktime',
                      // })
                      wx.navigateTo({
                        url: '/pages/booktime-center/booktime-center'
                      });
                      // wx.navigateBack({
                      //   delta: 1
                      // })
                    });
                  } else {
                    var contentname = util.orgid == 20510 ? (tc == 1 ? '預約失敗' : '預約失敗') :tc == 1 ? '預約失敗' : '预约失败';
                    wx.showToast({
                      title: contentname,
                    })
                  }

                  // that.getWaithao();
                  // that.getMyhao();
                }
              });
            }else{
              wx.showModal({
                title: util.orgid == 20510 ? (tc == 1 ? '你在該時間段已有預約' : '你在該時間段已有預約') :tc == 1 ? '你在該時間段已有預約' : "你在该时间段已有预约",
                // content: tc == 1 ? '你在該時間段已有預約' : "你在该时间段已有预约",
              })
            }
            
          })
          
        } else {
          wx.showToast({
            title: util.orgid == 20510 ? (tc == 1 ? '時間段不能預約' : '時間段不能預約') :tc == 1 ? '時間段不能預約' :'时间段不能预约',
          })
        }
      });
      

    }
   
    
  },
  yuyueConfigSubmit: function (e) {
    console.log(e);

    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'yuyueConfig' + that.data.token);
    util.api({
      method: "post",
      data: {
        ac: "yuyueConfig",
        uid: that.data.uid,
        orgid: that.data.postuid,
        privatekey: privatekey,
        date: that.getYMDString(that.data.currentObj),
        btime: that.data.btime[e.currentTarget.dataset.index].value,
        number: e.detail.value,
      },

      success: function (responseData) {
        console.log("调试--預約設置接口:", responseData.data);
        if (responseData.data.res == true) {
          var contentname = that.data.tc == 1 ? '預約設置已成功' : '預約設置已成功';
          
          console.log(contentname);
          app.dialogToast(contentname, "success", function () {
            // wx.navigateTo({ url: '/pages/booktime-center/booktime-center' });
          });

        } else {
          var contentname = that.data.tc == 1 ? '預約設置失敗' : '預約設置失败';
          wx.showToast({
            title: contentname,
          })
        }
        that.getWaithaoConfig();
        // that.getWaithao();
        // that.getMyhao();
      }
    });
  },

  //刷新当前页
  refreshPage: function() {
      wx.redirectTo({
          url:'/pages/booktime/booktime'
      })
  },


  //点击输入人数
  numberInput:function(e){
    this.setData({
      numberV: e.detail.value
    })
  },


  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({ url: path });
    }

    path = e.detail.value.page_path;
    if (path) {
      wx.navigateTo({ url: path });
    }
  },

  bindPickerChange: function (e) {
    var name = e.currentTarget.dataset.name;
    if (name == "btime") {
      this.setData({
        btimeIndex: e.detail.value
      })
    } else if (name == "project") {
      this.setData({
        projectIndex: e.detail.value
      })
    }
  },
  doDay: function (e) {
    var that = this
    var currentObj = that.data.currentObj
    var Y = currentObj.getFullYear();
    var m = currentObj.getMonth() + 1;
    var d = currentObj.getDate();
    var str = ''
    if (e.currentTarget.dataset.key == 'left') {
      m -= 1
      if (m <= 0) {
        str = (Y - 1) + '/' + 12 + '/' + d
      } else {
        str = Y + '/' + m + '/' + d
      }
    } else if (e.currentTarget.dataset.key == 'right'){
      m += 1
      if (m <= 12) {
        str = Y + '/' + m + '/' + d
      } else {
        str = (Y + 1) + '/' + 1 + '/' + d
      }
    }
    currentObj = new Date(str)
    console.log("currentObj：",currentObj)
    this.setData({
      currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
      currentObj: currentObj
    })
    this.setSchedule(currentObj);
    that.getWaithaoConfig();
  },
  getCurrentDayString: function () {
    var objDate = this.data.currentObj
    if (objDate != '') {
      return objDate
    } else {
      var c_obj = new Date()
      var a = c_obj.getFullYear() + '/' + (c_obj.getMonth() + 1) + '/' + c_obj.getDate()
      return new Date(a)
    }
  },
  setSchedule: function (currentObj) {
    var that = this
    var m = currentObj.getMonth() + 1
    var Y = currentObj.getFullYear()
    var d = currentObj.getDate();
    // var dayString = Y + '/' + m + '/' + currentObj.getDate()
    var currentDayNum = new Date(Y, m, 0).getDate();
    console.log("currentDayNum-------------->>>>>>>>>>>>>", currentDayNum);
    currentObj.setDate(1);
    var firstKey = currentObj.getDay();
    var firstKey = firstKey == 0 ? 7 : firstKey;
    var currentDayList = []
    var f = 0
    for (var i = 0; i < 42; i++) {
      let data = []
      if (i < firstKey - 1) {
        currentDayList[i] = ''
      } else {
        if (f < currentDayNum) {
          currentDayList[i] = f + 1
          f = currentDayList[i]
        } else if (f >= currentDayNum) {
          currentDayList[i] = ''
        }
      }
    }
    let dateList=[];
    for (var i = 0; i < 42; i++){
      let obj={};
      obj.index = i;
      obj.date = currentDayList[i];
      let btime = [
        { value: "上午09-10點", number: 0, counts: 0 },
        { value: "上午10-11點", number: 0, counts: 0 },
        { value: "下午14-15點", number: 0, counts: 0 },
        { value: "下午15-16點", number: 0, counts: 0 },
        { value: "下午16-17點", number: 0, counts: 0 },
        { value: "晚上18-19點", number: 0, counts: 0 },
        { value: "晚上19-20點", number: 0, counts: 0 },
        { value: "晚上20-21點", number: 0, counts: 0 }];
      obj.btime = btime;
      obj.dateObj = new Date(Y, currentObj.getMonth(), obj.date)
      obj.state = 1;
      dateList.push(obj);      
    }
    let btime = [
      { value: "上午09-10點", number: 0, counts: 0 },
      { value: "上午10-11點", number: 0, counts: 0 },
      { value: "下午14-15點", number: 0, counts: 0 },
      { value: "下午15-16點", number: 0, counts: 0 },
      { value: "下午16-17點", number: 0, counts: 0 },
      { value: "晚上18-19點", number: 0, counts: 0 },
      { value: "晚上19-20點", number: 0, counts: 0 },
      { value: "晚上20-21點", number: 0, counts: 0 }];
    that.setData({      
      currentDayList: dateList,
      btime: btime
    })
  } ,

  sliderChange: function (e) {
    var that=this;
    
    if (this.data.currentObj>=this.data.today){
      that.setData({
        cannotSlide: false
      })

      // that.data.btime[e.currentTarget.dataset.index].number = e.detail.value;
      // for (var i = 0; i < 42; i++) {
      //   if (that.data.currentDay == that.data.currentDayList[i].date) {
      //     that.data.currentDayList[i].btime = that.data.btime;
      //     that.setData({
      //       btime: that.data.currentDayList[i].btime
      //     })
      //     console.log(that.data.currentDayList[i])
      //   }
      // }
      this.yuyueConfigSubmit(e);
      
    }else{
      wx.showToast({
        title: '日期已過',
      })
      that.setData({
        cannotSlide:true
      })
    }
    // if (this.data.uid == '16132') {
    // }else{
    //   wx.showToast({
    //     title: '無管理員權限',
    //   })
    //   that.setData({
    //     cannotSlide: true
    //   })
    // }
  },

  dateSelected:function(e){
    var that=this;
    console.log("currentDateObj", this.data.currentObj);
    console.log("e", e.currentTarget.dataset.date);
    if (e.currentTarget.dataset.date != '') {
      this.data.currentObj.setDate(e.currentTarget.dataset.date);

    }
    var currentObj=this.data.currentObj;
    
    // this.getWaithaoConfig()
    // this.loadDataToList();
    if (this.data.currentObj >= this.data.today) {
      that.setData({
        cannotSlide: false
      })
      for (var i = 0; i < 42; i++) {
        if (e.currentTarget.dataset.date && e.currentTarget.dataset.date == this.data.currentDayList[i].date) {
          this.setData({
            btime: this.data.currentDayList[i].btime,
            currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
            currentDay: currentObj.getDate(),
            currentObj: currentObj,
            date: that.getYMDString(that.data.currentObj),
          })
          console.log(this.data.currentDayList[i])
        }
      }
    } else if (this.data.currentObj!=''){
      this.setData({
        btime: [],
        currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
      })
      that.setData({
        cannotSlide: true
      })
      // wx.showToast({
      //   title: '日期已過',
      // })
    }
  },

  //时间戳转换时间 

  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    return (Y + M + D + " | " + H + ':' + m)
  },

  //返回日期6/29/2018格式
  getYMDString:function(dateObj){
    var Y = dateObj.getFullYear();
    var M = (dateObj.getMonth() + 1 < 10 ? '' + (dateObj.getMonth() + 1) : dateObj.getMonth() + 1) + '/';
    var D = dateObj.getDate() < 10 ? ('0' + dateObj.getDate() + '/') : dateObj.getDate() + '/';
    return (M + D + Y)
  },

  getDate: function(str){
    var arr=[];
    arr=str.split('|');
    return arr[0];

  },
  getTime: function(str){
    var arr = [];
    arr = str.split('|');
    return arr[1];
  },

  //载入预约设置信息
  loadConfigToList:function(){
    var that = this;
    var waithaoConfig = that.data.waithaoConfig;

    var currentDayList = that.data.currentDayList;
    var btime = that.data.btime;
    for (var i = 0; i < 42; i++) {
      for (var k = 0; k < btime.length; k++) {
        for (var j = 0; j < waithaoConfig.length; j++) {
          if (that.getYMDString(currentDayList[i].dateObj) == waithaoConfig[j].date && currentDayList[i].btime[k].value == waithaoConfig[j].btime){
            currentDayList[i].btime[k].number = waithaoConfig[j].number;
          }
        } 
      }
    }
    that.loadDataToList();
  },

  //载入用户预约信息
  loadDataToList:function(){
    var that = this;
    var currentDayList = that.data.currentDayList;
    
    var waithao=that.data.waithao;
    console.log('waithao.length', waithao.length);
    var btime=that.data.btime;
    for (var i = 0; i < 42; i++) {
      currentDayList[i].state = 0;
      for (var k = 0; k < btime.length;k++){
        currentDayList[i].btime[k].counts = 0;
        for (var j = 0; j < waithao.length; j++) {
          
          if (that.getYMDString(currentDayList[i].dateObj) == that.getDate(waithao[j].btime) && currentDayList[i].btime[k].value.substring(2, 4) == that.getTime(waithao[j].btime).substring(0, 2)){
            currentDayList[i].btime[k].counts++;
            console.log(that.getDate(waithao[j].btime),"+", that.getTime(waithao[j].btime).substring(0, 2))
            console.log("count++", currentDayList[i].btime[k].counts);
          }
        }        
        if (currentDayList[i].btime[k].number > currentDayList[i].btime[k].counts) {
          currentDayList[i].state = 1;
        }
      }
      
    } 
    console.log('loadDataToList::::currentDayList------>>>>',currentDayList);
    that.setData({
      currentDayList: currentDayList,
    })
    //更新当前日期btime
    var currentObj = that.data.currentObj
    for (var i = 0; i < 42; i++) {
      if (currentObj.getDate() == currentDayList[i].date) {
        that.setData({
          btime: currentDayList[i].btime,

          currentDateStr: currentObj.getFullYear() + '年' + (currentObj.getMonth() + 1) + '月' + currentObj.getDate() + '日',
          currentDay: currentObj.getDate(),
          currentObj: currentObj
        })
        console.log(this.data.currentDayList[i])
      }
    }
    // 17597我的
    if (this.data.uid == '16131' || this.data.uid == '17598' || that.data.isAdmin== true) {
      that.setData({
        cannotSlide: false,
        isAdmin:true
      })
    } else {
      // wx.showToast({
      //   title: '無管理員權限',
      // })
      that.setData({
        cannotSlide: true
      })
    }
  },
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var dateArr = [];
    dateArr = e.detail.value.split('-');
    var dateStr = dateArr[1].replace(/\b(0+)/gi, "") + '/' + dateArr[2] + '/' + dateArr[0]
    this.setData({
      date: dateStr
    })
  },

  bindTimeChange: function (e) {
    console.log('时间picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  //检查预约时间段是否可约，时间段预约数是否已满
  checkCounts: function (cb){
    var that = this;
    
    var currentDayList = that.data.currentDayList;

    console.log('checkCounts');
    var btime = that.data.btime;
    
    util.api({
      method: "get",
      data: {
        ac: "checkcounts",
        
        orgid: that.data.postuid,
        date: that.data.date,
        time: that.data.time,
      },

      success: function (responseData) {
        console.log("调试--checkCounts接口:", responseData.data);
        var result = responseData.data.res;
        typeof cb == "function" && cb(result);
      }
    });

  },
  //检查本人在时间段内是否已经预约过
  checkMyhao:function(cb){
    var that=this;
    util.api({
      method: "get",
      data: {
        ac: "checkmyhao",
        uid: that.data.uid,
        ghsid: that.data.postuid,
        date: that.data.date,
        time: that.data.time,
      },

      success: function (responseData) {
        console.log("调试--checkmyhao接口:", responseData.data);
        var result = responseData.data.res;
        typeof cb == "function" && cb(result);
      }
    });
  },
  selectTime:function(e){
    console.log('e.currentTarget.dataset', e.currentTarget.dataset);
    console.log('e.currentTarget.dataset.timeselected', e.currentTarget.dataset.timeselected);

    var that = this;
    var timeselected = e.currentTarget.dataset.timeselected;
    for (var i = 0; i < that.data.btime.length; i++) {
      if (timeselected == that.data.btime[i].value){
        that.data.btime[i].selected=true;
        if (that.data.btime[i].number > that.data.btime[i].counts){
          wx.showToast({
            title: '已選' + timeselected,
          })
        }else{
          wx.showToast({
            title: '時間段不能選擇'
          })
        }
      }else{
        that.data.btime[i].selected = false;
      }
    }
    that.setData({
      btime: that.data.btime,
      btimeselected: timeselected,
      date: that.getYMDString(that.data.currentObj),
      time: timeselected.substring(2, 4)+":00"
    })
    
  },
  
  hideSchedule:function(){
    var that = this;
    that.hideModal();
  },

  showModal: function () {
    var that=this;
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      scheduleShow: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        scheduleShow: true
      })
    }.bind(this), 200);
    that.getWaithao();
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        scheduleShow: false
      })
    }.bind(this), 200)
  },
  //下拉选项改变值
  bindGhsPickerChange: function (e) {//选项改变触发事件
    var that=this;
    this.setData({
      ghsIndex: e.detail.value
    })
    this.setData({
      postuid:this.data.ghsIdList[this.data.ghsIndex],
      project: this.data.ghsList[this.data.ghsIndex].project_list
    })
    console.log("postuid", this.data.postuid);
    this.setSchedule(that.data.currentObj);
    that.getWaithao();
  },
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },   

  //获取用户认证状态
  getAuth: function (uid, token) {
    var that = this;
    
    var privatekey = utilMd5.hexMD5(uid + 'getUserAuth' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getUserAuth",
        uid: uid,
        catatype: '20',
        privatekey: privatekey
      },
      method: 'GET',
      success: function (responseData) {
        var data = responseData.data;
        console.log("获取已提交的认证信息：", data);
        if (data && data.res != false && data.realname) {
          //更新数据
          that.setData({
            authData: data,
            userV: data.realname ? data.realname : '',
            phoneV: data.phone ? data.phone : '',
            location: data.location ? data.location : '',
          });
          if (that.data.authData.verified != '1') {

            var tc = that.data.tc;
            // wx.showModal({
            //   title: tc == -1 ? 'You are not a member. Please register.' : tc == 1 ? '你不是會員，請註冊' : '你不是会员，请注册',
            //   confirmText: tc == -1 ? 'REGISTER' : tc == 1 ? '註冊' : '注册',
            //   cancelText: tc == -1 ? 'cancel' : tc == 1 ? '取消' : '取消',
            //   success: function (res) {
            //     if (res.confirm) {
            //       wx.navigateTo({
            //         url: '/pages/agent/agent',
            //       })
            //       console.log('用户点击确定')
            //     } else if (res.cancel) {
            //       wx.navigateBack({
            //         delta: 1
            //       })
            //       console.log('用户点击取消')
            //     }
            //   }
            // })
            return
          }
        } else {
          that.setData({
            authData: ''
          });
        }
      }
    });
  },
})